package com.hcj.springcloud.ProxyPattern.JdkAndCglibProxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib 代码执行耗时的方法拦截器
 */
public class CostTimeProxyInterceptor implements MethodInterceptor {
    private Object target;

    public CostTimeProxyInterceptor(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = method.invoke(this.target, objects);
        long end = System.currentTimeMillis();
        System.out.println(this.target.getClass() + "." + method.getName() + "() 耗时：" + (end - start));
        return result;
    }


    public static <T> T createProxy(T target) {
        CostTimeProxyInterceptor costTimeProxyInterceptor = new CostTimeProxyInterceptor(target);
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(costTimeProxyInterceptor);
        enhancer.setSuperclass(target.getClass());
        return (T) enhancer.create();
    }
}
